//
//  MessageViewController.m
//  huanxin
//
//  Created by 郭亚 on 16/4/28.
//  Copyright © 2016年 郭亚. All rights reserved.
//

#import "MessageViewController.h"

#import "MessageTableViewCell.h"

#import "ContentViewController.h"

#import <EaseMob.h>

@interface MessageViewController ()<UITableViewDataSource, UITableViewDelegate, EMChatManagerDelegate>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *dataArray;

@end

@implementation MessageViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    _dataArray = [NSMutableArray array];
    [self createView];
    self.navigationItem.title = @"聊天列表";
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:dispatch_get_main_queue()];
    [self reloadConvercation];
}


- (void)createView
{
    _tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:(UITableViewStylePlain)];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    _tableView.tableFooterView = [[UIView alloc] init];
    [_tableView registerClass:[MessageTableViewCell class] forCellReuseIdentifier:@"cell"];
    
}
// 获取数据 获取的是当前用户的 会话列表
- (void)reloadConvercation
{
    [_dataArray removeAllObjects];
    
    // 获取当前用户的会话列表的方式
    [_dataArray addObjectsFromArray: [[EaseMob sharedInstance].chatManager loadAllConversationsFromDatabaseWithAppend2Chat:YES]];
    
    [_tableView reloadData];
}

#pragma mark EMChatManagerDelegate 代理方法
// 收到一条消息
- (void)didReceiveMessage:(EMMessage *)message
{
    [self reloadConvercation];
}

#pragma mark EMChatManagerDelegate 收到好友请求的代理方法
// 第一个参数 : 好友姓名
// 第二个参数 : 请求信息
- (void)didReceiveBuddyRequest:(NSString *)username message:(NSString *)message
{
    NSString *title = [NSString stringWithFormat:@"%@请求添加您为好友", username];
    UIAlertController *controller = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:(UIAlertControllerStyleAlert)];
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"好的" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        // 环信错误类 相当于NSError
        EMError *error = nil;
        // 接受好友信息
        BOOL succeed = [[EaseMob sharedInstance].chatManager acceptBuddyRequest:username error:&error];
        if (succeed && !error) {
            NSLog(@"接受成功");
        }
        
    }];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"滚犊子" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        EMError *error = nil;
        BOOL succeed = [[EaseMob sharedInstance].chatManager rejectBuddyRequest:username reason:@"去吃翔吧~" error:&error];
        if (succeed && !error) {
            NSLog(@"拒绝成功");
        }
    }];
    
    [controller addAction:action];
    [controller addAction:action1];
    [self presentViewController:controller animated:YES completion:nil];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MessageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    // 聊天会话对象
    EMConversation *conversation = _dataArray[indexPath.row];
    // chatter 会话对象中的名字
    cell.friendName.text = conversation.chatter;
    // message聊天的对象 conversation.latesMessage最后一条消息
    EMMessage *message = conversation.latestMessage;
    //EMTextMessageBody 消息体对象, message.messageBodies 聊天消息中保存的消息体的对象
    // 获取到最后一次发送的消息
    EMTextMessageBody *body = message.messageBodies.lastObject;
    
    cell.content.text = body.text;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ContentViewController *contentVC = [[ContentViewController alloc] init];
    
    EMConversation *conversation = _dataArray[indexPath.row];
    // chatter 聊天的对象
    contentVC.chatter = conversation.chatter;
        
    [self.navigationController pushViewController:contentVC animated:YES];
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
